/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.web.firefox.mozrepl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Peter De Bruycker
 */
public class MozRepl {

    public static final String DEFAULT_HOST = "localhost";
    public static final int DEFAULT_PORT = 4242;

    private String host;
    private int port;

    private Socket connection;
    private String banner;

    public MozRepl(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect() {
        if (isConnected()) {
            throw new MozReplException("Already connected");
        }

        try {
            connection = new Socket(host, port);

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // not gonna happen
                throw new MozReplException(e);
            }
            banner = readResponse(connection.getInputStream());
        } catch (UnknownHostException e) {
            throw new MozReplException(e);
        } catch (IOException e) {
            throw new MozReplException(e);
        }
    }

    public void disconnect() {
        if (!isConnected()) {
            throw new MozReplException("Not yet connected");
        }

        try {
            connection.close();
        } catch (IOException e) {
            throw new MozReplException(e);
        } finally {
            connection = null;
        }
    }

    public boolean isConnected() {
        return connection != null;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getBanner() {
        return banner;
    }

    public String sendAndReceive(String text) {
        try {
            send(text);

            // give mozRepl some time to react
            // TODO fix this
            Thread.sleep(250);

            return readResponse(connection.getInputStream());
        } catch (IOException e) {
            throw new MozReplException(e);
        } catch (InterruptedException e) {
            // not gonna happen
            throw new MozReplException(e);
        }
    }

    public void send(String text) {
        if (!isConnected()) {
            throw new MozReplException("Not yet connected");
        }

        try {
            OutputStream output = connection.getOutputStream();
            output.write(text.getBytes());
            output.write('\n');
        } catch (IOException e) {
            throw new MozReplException(e);
        }
    }

    private String readResponse(InputStream input) throws IOException {
        StringBuilder sb = new StringBuilder();

        do {
            char ch = (char) input.read();
            sb.append(ch);
        } while (input.available() > 0);

        String response = sb.toString();

        if (Pattern.matches("(\\.)+> ", response)) {
            // error
            throw new MozReplException(response);
        }

        Pattern p = Pattern.compile("((.*\\n?)+)\\nrepl\\d*> ");
        Matcher matcher = p.matcher(response);
        if (matcher.matches()) {
            response = matcher.group(1);
            if (response.startsWith("\"")) {
                response = response.substring(1);
            }
            if (response.endsWith("\"")) {
                response = response.substring(0, response.length() - 1);
            }

            return response;
        }

        throw new MozReplException(response + " has incorrect format");
    }
}
